package com.dmap.knowledge.service.impl;

import com.dmap.knowledge.bo.company.CompanyAPPInfo;
import com.dmap.knowledge.controller.api.param.ArticleAppParam;
import com.dmap.knowledge.controller.api.param.ArticleEditParam;
import com.dmap.knowledge.controller.api.param.ArticleParam;
import com.dmap.knowledge.controller.api.param.ArticleTagParam;
import com.dmap.knowledge.dao.ArticleMapper;
import com.dmap.knowledge.po.Article;
import com.dmap.knowledge.po.ArticleTag;
import com.dmap.knowledge.rpc.CompanyServiceRpc;
import com.dmap.knowledge.service.ArticleColumnService;
import com.dmap.knowledge.service.ArticleExtensionService;
import com.dmap.knowledge.service.ArticleService;
import com.dmap.knowledge.service.ArticleTagService;
import com.dmap.knowledge.vo.ArticleInfoOneVo;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    private static final Logger logger = Logger.getLogger(ArticleServiceImpl.class);

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private ArticleTagService articleTagService;
    @Resource
    private CompanyServiceRpc companyServiceRpc;
    @Resource
    private ArticleColumnService articleColumnService;
    @Resource
    private ArticleExtensionService articleExtensionService;

    @Override
    public Article selectByArticleId(long id) {
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<String> getArticleTagNames(long articleId) {
        List<String> articleTagNames = new ArrayList<>();
        List<ArticleTag> articleTagList = articleTagService.selectByArticleId(articleId);
        articleTagList.forEach(articleTag -> articleTagNames.add(articleTag.getTagName()));
        return articleTagNames;
    }

    @Override
    public List<Integer> createRandom(int maxNumber) {
        /**
         * 两个两个以上
         */
        int randomOne = (int) (0 + Math.random() * (maxNumber + 1)); //从0到7的int型随数
        int randomTwo = (int) (0 + Math.random() * (maxNumber + 1)); //从0到7的int型随数
        List<Integer> arr = new ArrayList<>();
        arr.add(randomOne);
        if (arr.indexOf(randomTwo) != -1) {
            return createRandom(maxNumber);
        }
        arr.add(randomTwo);
        return arr;
    }


    @Override
    public int insertArticle(ArticleParam param) {
        List<ArticleAppParam> appList = param.getAppList();
        for (ArticleAppParam articleAppParam : appList) {
            Article article = new Article();
            article.setLang(param.getLang().toUpperCase());
            article.setCoverUrl(param.getCoverUrl());
            article.setArticleUrl(param.getArticleUrl());
            article.setSummary(param.getSummary());
            article.setTitle(param.getTitle());
            article.setAuthorName(param.getAuthorName());
            article.setUploaderId(Long.parseLong(param.getUploaderId()));
            article.setPublishTime(param.getStartTime());
            article.setUsefulTime(param.getEndTime());
            article.setAppNumber(articleAppParam.getAppNumber());
            //rpc 调用
            CompanyAPPInfo companyAPPInfo = companyServiceRpc.selectCompanyAppInfo(articleAppParam.getAppNumber());
            article.setCompanyNumber(companyAPPInfo.getCompanyNumber());
            article.setCompanyId(companyAPPInfo.getCompanyId());
            article.setAppId(companyAPPInfo.getAppId());
            article.setAppName(companyAPPInfo.getAppName());
            article.setColumnId(Long.parseLong(articleAppParam.getColumnId()));
            article.setColumnName(articleAppParam.getColumnName());
            article.setAppName(articleAppParam.getAppName());
            List<ArticleTagParam> articleTagList = param.getTags();
            StringBuilder tagNames = new StringBuilder();
            articleTagList.forEach(articleTags -> {
                tagNames.append(articleTags.getTagName() + ",");
            });
            article.setTagNames(tagNames.toString().substring(0, tagNames.toString().lastIndexOf(",")));
            article.setPromulgatorId(0L);
            article.setCreateTime(System.currentTimeMillis() / 1000);
            article.setUpdateTime(System.currentTimeMillis() / 1000);
            int success = articleMapper.insertSelective(article);
            if (success == 0) {
                return 0;
            }
            int count = 0;
            for (ArticleTagParam articleTag : articleTagList) {
                count = count + articleTagService.insertArticleTag(article.getId(), Long.parseLong(articleTag.getTagTypeId()), articleTag.getTagTypeName(), Long.parseLong(articleTag.getTagId()), articleTag.getTagName(), System.currentTimeMillis() / 1000);
            }
            if (count != articleTagList.size()) {
                return 0;
            }
            //修改热门文章缓存
            articleExtensionService.updateHotArticleCachePo(article.getLang(),article.getAppNumber());
            //修改今日文章推荐缓存
            articleExtensionService.updateTodayArticleCachePo(article.getLang(),article.getAppNumber());
        }

        return 1;
    }

    @Transactional
    @Override
    public int updateArticle(ArticleEditParam param) {
        ArticleAppParam articleEditParamApp = param.getApp();
        Article article = new Article();
        article.setId(Long.parseLong(param.getArticleId()));
        article.setLang(param.getLang().toUpperCase());
        article.setCoverUrl(param.getCoverUrl());
        article.setArticleUrl(param.getArticleUrl());
        article.setSummary(param.getSummary());
        article.setTitle(param.getTitle());
        article.setPublishTime(param.getStartTime());
        article.setUsefulTime(param.getEndTime());
        article.setUpdateTime(System.currentTimeMillis() / 1000);
        article.setAppName(param.getApp().getAppName());
        //rpc 调用
        CompanyAPPInfo companyAPPInfo = companyServiceRpc.selectCompanyAppInfo(articleEditParamApp.getAppNumber());
        article.setCompanyId(companyAPPInfo.getCompanyId());
        article.setCompanyNumber(companyAPPInfo.getCompanyNumber());
        article.setAppId(companyAPPInfo.getAppId());
        article.setAppNumber(articleEditParamApp.getAppNumber());
        article.setAppName(companyAPPInfo.getAppName());
        article.setColumnId(Long.parseLong(articleEditParamApp.getColumnId()));
        article.setColumnName(articleEditParamApp.getColumnName());
        List<ArticleTagParam> articleTagList = param.getTags();
        StringBuilder tagNames = new StringBuilder();
        articleTagList.forEach(articleTags -> {
            tagNames.append(articleTags.getTagName() + ",");
        });
        article.setTagNames(tagNames.toString().substring(0, tagNames.toString().lastIndexOf(",")));
        article.setUpdateTime(System.currentTimeMillis() / 1000);
        int success = articleMapper.updateByPrimaryKeySelective(article);
        int articleDeleteSuccess = articleTagService.deleteArticleTagByArticleId(article.getId());
        if (success == 0 && articleDeleteSuccess == 0) {
            return 0;
        }
        int count = 0;
        for(ArticleTagParam articleTagParam:articleTagList){
            count += articleTagService.insertArticleTag(article.getId(), Long.parseLong(articleTagParam.getTagTypeId()), articleTagParam.getTagTypeName(), Long.parseLong(articleTagParam.getTagId()), articleTagParam.getTagName(), System.currentTimeMillis() / 1000);

        }
        if (count == articleTagList.size()) {
            return 1;
        }
        //修改热门文章缓存
        articleExtensionService.updateHotArticleCachePo(article.getLang(),article.getAppNumber());
        //修改今日文章推荐缓存
        articleExtensionService.updateTodayArticleCachePo(article.getLang(),article.getAppNumber());
        return 0;
    }

    @Transactional
    @Override
    public int deleteArticleById(long articleId) {
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article == null) {
            return 0;
        }

        articleTagService.deleteArticleTagByArticleId(article.getId());
        int success =  articleMapper.deleteByPrimaryKey(articleId);
        //修改热门文章缓存
        articleExtensionService.updateHotArticleCachePo(article.getLang(),article.getAppNumber());
        //修改今日文章推荐缓存
        articleExtensionService.updateTodayArticleCachePo(article.getLang(),article.getAppNumber());
        return success;
    }

    @Override
    public int updateArticleAudit(String articleId) {
        Article article = articleMapper.selectByPrimaryKey(Long.parseLong(articleId));
        if (article == null) {
            return 0;
        }
        //2代表审核通过
        article.setAudit(2);
        int success = articleMapper.updateByPrimaryKeySelective(article);
        if (success == 0) {
            return 0;
        }
        //修改热门文章缓存
        articleExtensionService.updateHotArticleCachePo(article.getLang(),article.getAppNumber());
        //修改今日文章推荐缓存
        articleExtensionService.updateTodayArticleCachePo(article.getLang(),article.getAppNumber());
        return 1;
    }

    @Override
    public int updateArticlePublish(String articleId, String promulgatorId) {
        Article article = articleMapper.selectByPrimaryKey(Long.parseLong(articleId));
        if (article == null) {
            return 0;
        }
        //1发布 2未未发布
        if (article.getPublish() == 1) {
            article.setPublish(2);
        } else {
            article.setPublish(1);
        }
        article.setPublishTime(System.currentTimeMillis()/1000);
        article.setUpdateTime(System.currentTimeMillis()/1000);
        article.setPromulgatorId(Long.parseLong(promulgatorId));

        int success = articleMapper.updateByPrimaryKey(article);
        if (success == 0) {
            return 0;
        }
        logger.debug("或农村开始。。。。。。。。。。。。。。。");

        //修改热门文章缓存
        articleExtensionService.updateHotArticleCachePo(article.getLang(),article.getAppNumber());
        //修改今日文章推荐缓存
        articleExtensionService.updateTodayArticleCachePo(article.getLang(),article.getAppNumber());
        logger.debug("缓存结束。。。。。。。。。。。");
        return 1;
    }


    @Override
    public ArticleInfoOneVo selectArticleInfo(String articleId) {
        Article article = articleMapper.selectByPrimaryKey(Long.parseLong(articleId));
        if (article == null) {
            return null;
        }
        ArticleInfoOneVo articleInfoOneVo = new ArticleInfoOneVo(article);
        articleInfoOneVo.getApp().setAppName(article.getAppName());
        articleInfoOneVo.getApp().setColumnName(article.getColumnName());
        articleInfoOneVo.getApp().setColumnId(article.getColumnId().toString());
        articleInfoOneVo.getApp().setAppNumber(article.getAppNumber());
        List<ArticleTag> articleTags = articleTagService.selectByArticleId(Long.parseLong(articleId));
        articleTags.forEach(articleTag -> articleInfoOneVo.getTags().add(new ArticleTagParam(articleTag)));
        return articleInfoOneVo;
    }

    @Transactional
    @Override
    public int deleteArticleList(String articleIds) {
        List<String> articleIdList = Arrays.asList(articleIds.split(","));
        int count = 0;
        for (String articleId : articleIdList) {
            count += deleteArticleById(Long.parseLong(articleId));
        }
        if (count == articleIdList.size()) {
            return 1;
        }
        return 0;
    }

}
